package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;
    /**
     * 统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
           TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
           //统计日期集合
           List<LocalDate> dateList=new ArrayList<>();
           dateList.add(begin);
           while(!begin.equals(end)) {
               begin=begin.plusDays(1);
               dateList.add(begin);
           }
           turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
           //统计营业额
           List<Double>  turnoverList=new ArrayList<>();
           for(LocalDate date : dateList) {
               //查询对应日期的营业额，营业额是指当天状态为已完成的的订单，同时时间具体到时分秒
               LocalDateTime beginDateTime=LocalDateTime.of(date, LocalTime.MIN);
               LocalDateTime endDateTime=LocalDateTime.of(date, LocalTime.MAX);
               //封装查询的参数
               Map map=new HashMap();
               map.put("begin",beginDateTime);
               map.put("end",endDateTime);
               map.put("status", Orders.COMPLETED);
               Double turnover=orderMapper.sumByMap(map);
               turnover=turnover!=null?turnover:0;
               turnoverList.add(turnover);
           }
           turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
           return turnoverReportVO;
    }

    /**
     * 统计用户数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //先获取日期列表
        List<LocalDate> list=new ArrayList<>();
        //循环获取
        list.add(begin);
        while(!begin.equals(end)) {
            begin=begin.plusDays(1);
            list.add(begin);
        }
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        for (LocalDate localDate : list) {
            //先将日期加上时分
            LocalDateTime beginTime=LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(localDate,LocalTime.MAX);
            Map map=new HashMap();
            //查询总用户量
            map.put("end",endTime);
            Integer total=userMapper.countUserByMap(map);
            totalUserList.add(total);
            //查询新增用户量
            map.put("begin",beginTime);
            Integer news=userMapper.countUserByMap(map);
            newUserList.add(news);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(list,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 统计订单数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)) {
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //创建每天总单数的列表
        List<Integer> orderList=new ArrayList<>();
        //创建每天有效的单数的列表
        List<Integer> validOrderList=new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //获取每天的总单量
            Integer orders=getOrder(beginTime,endTime,null);
            orderList.add(orders);
            //获取每天的有效单量
            Integer validOrders = getOrder(beginTime, endTime, Orders.COMPLETED);
            validOrderList.add(validOrders);
        }
        //获取时间段内的总订单量
        Integer total=orderList.stream().reduce( Integer::sum).get();
        //获取时间段内有效的总订单量
        Integer validTotal = validOrderList.stream().reduce(Integer::sum).get();
        //获取有效的订单率
        Double orderCompletionRate=validTotal.doubleValue()/total;
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderList,","))
                .validOrderCountList(StringUtils.join(validOrderList,","))
                .totalOrderCount(total)
                .validOrderCount(validTotal)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计销量Top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //TODO:不确定用哪个mapper order sql语句不熟
        //TODO:number别名不能改
        List<GoodsSalesDTO> top10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> nameList = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String names = StringUtils.join(nameList, ",");
        List<Integer> numberList = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbers = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO.builder().nameList(names).numberList(numbers).build();
    }

    /**
     * 统计excel报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {
       //1.查询数据库，获取营业数据
        //先获取日期
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2.通过POI将数据写入excel文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheet("sheet1");
        //填入日期
        sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
        //填入数据概览
        sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
        //明细表
        for(int i=0,row=7;i<30;i++,row++){
            LocalDate localDate=begin.plusDays(i);
            BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
            sheet.getRow(row).getCell(1).setCellValue(localDate.toString());
            sheet.getRow(row).getCell(2).setCellValue(data.getTurnover());
            sheet.getRow(row).getCell(3).setCellValue(data.getValidOrderCount());
            sheet.getRow(row).getCell(4).setCellValue(data.getOrderCompletionRate());
            sheet.getRow(row).getCell(5).setCellValue(data.getUnitPrice());
            sheet.getRow(row).getCell(6).setCellValue(data.getNewUsers());
        }
        //3.通过输出流将excel文件写入浏览器文件
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);

    }

    /**
     * 获取对应条件的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrder(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map=new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }




}
